package com.inspur.incubator.common.tools;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import oracle.net.aso.s;
import net.sf.json.JSONArray;

public class Export {
    /** CSV文件列分隔符 */
    private static final String CSV_COLUMN_SEPARATOR = ",";

    /** CSV文件列分隔符 */
    private static final String CSV_RN = "\r\n";

    public static boolean doExport(String agent,JSONArray dataList,JSONArray cName1, OutputStream os,String fName,HttpServletResponse response) throws UnsupportedEncodingException, IOException {
        
            StringBuffer buf = new StringBuffer();
            
            for(int i=0;i<cName1.size();i++){
                buf.append(cName1.get(i)).append(CSV_COLUMN_SEPARATOR);
            }
             
            buf.append(CSV_RN);
 
            
            String timeName = ""; 
            if (null != dataList) {
            	if(cName1.contains("序号"))
            	{
            		for (int i = 0; i <dataList.size(); i++) {
                    	JSONArray cellList = (JSONArray) dataList.get(i);
                    	if(cellList.size() >0)
                    	{
                    		for (int j = 0; j < cellList.size(); j++) {
                            	if(StringUtils.isNotBlank(String.valueOf(cellList.get(j))))
                            	{
                            		buf.append(cellList.get(j)).append(CSV_COLUMN_SEPARATOR);
                            	}
                            	 
                            }
                            buf.append(CSV_RN);
                    	}
                        
                    }
            	}else {
            		for (int i = dataList.size()-1; i > 0; i--) {
                    	JSONArray cellList = (JSONArray) dataList.get(i);
                        for (int j = 0; j < cellList.size(); j++) {
                        	if(StringUtils.isNotBlank(String.valueOf(cellList.get(j))))
                        	{
                        		buf.append(cellList.get(j)).append(CSV_COLUMN_SEPARATOR);
                        	}                        	 
                        }
                        buf.append(CSV_RN);
                    }
            		String sTime = "";
            		JSONArray cellList = (JSONArray) dataList.get(1);
                    for (int j = 0; j < cellList.size(); j++) {
                    	if(cellList.get(j).toString().contains("年"))
                    	{
                    		sTime = cellList.get(j).toString();
                    	}
                    }
                    
            		String eTime = "";
                    cellList = (JSONArray) dataList.get(dataList.size()-1);
                    for (int j = 0; j < cellList.size(); j++) {
                    	if(cellList.get(j).toString().contains("年"))
                    	{
                    		eTime = cellList.get(j).toString();
                    	}                    	 
                    }
                    if(eTime.equals(sTime))
                    {
                    	timeName = eTime;
                    }else {
                    	timeName = eTime+"至"+sTime;
					}
				}
            } 
            
            String fn =  timeName+fName + ".csv";
            // 读取字符编码
            String utf = "UTF-8";
            // 设置响应
            response.setContentType("application/ms-txt.numberformat:@");
            response.setCharacterEncoding(utf);
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "max-age=30");
             if(agent.contains("firefox"))
             {
            	  // 火狐中避免乱码：
                 fn = new String(fn.getBytes("utf-8"), "iso-8859-1");
                 response.setCharacterEncoding("utf-8");
                 response.setHeader("Content-disposition", "attachment;filename=" + fn);
             }else{
            	 
            	 response.setHeader("Content-Disposition", "attachment; filename=" +URLEncoder.encode(fn, utf).replaceAll("\\+", "%20").replaceAll("%28", "\\(").replaceAll("%29", "\\)").replaceAll("%3B", ";").replaceAll("%40", "@").replaceAll("%23", "\\#").replaceAll("%26", "\\&").replaceAll("%2C", "\\,"));
             }
              
            // 写出响应
            os.write(buf.toString().getBytes("GBK"));
            os.flush();
            os.close();
            return true;
        
         
    }

    /**
     * @throws UnsupportedEncodingException
     * 
     *             setHeader
     */
    public static void responseSetProperties(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
        // 设置文件后缀
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fn = fileName + ".csv";
        // 读取字符编码
        String utf = "UTF-8";

        // 设置响应
        response.setContentType("application/ms-txt.numberformat:@");
        response.setCharacterEncoding(utf);
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=30");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
        
    }
}
